package com.mazaiting.classpath;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.rmi.CORBA.Util;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * 读取压缩包中的 .class 文件
 *
 * @author mazaiting
 * @since 2021/8/10
 */
@Slf4j
@Data
public class ZipEntry implements Entry {
    /**
     * 绝对路径
     */
    private String absPath;

    public ZipEntry(String path) {
        this.absPath = FileUtil.getAbsolutePath(path);
    }

    @Override
    public ClassResponse readClass(String className) {
        ClassResponse classResponse = new ClassResponse();
        classResponse.setEntry(this);
        try {
            // TODO 待优化
            ZipFile zipFile = new ZipFile(absPath);
            ZipUtil.read(zipFile, zipEntry -> {
                if (ObjectUtil.equal(zipEntry.getName(), className)) {
                    try {
                        byte[] bytes = IoUtil.readBytes(ZipUtil.getStream(new ZipFile(absPath), zipEntry));
                        classResponse.setBytes(bytes);
                    } catch (IOException e) {
                        log.error("读取文件{}异常: {}", className, e.getMessage());
                    }
                }
            });
            // 如果没有读取到类信息
            if (ObjectUtil.isEmpty(classResponse.getBytes())) {
                classResponse.setError("class not found: " + className);
            }
        } catch (Exception e) {
            log.error("读取文件{}异常, {}", this.absPath, e.getMessage());
            classResponse.setError(e.getMessage());
        }
        return classResponse;
    }

    @Override
    public String toString() {
        return this.absPath;
    }
}


















